package com.alifi.crm.biz.lotteryzf;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.china.biz.common.util.DateUtil;
import com.alibaba.common.lang.StringUtil;
import com.alibaba.common.logging.Logger;
import com.alibaba.common.logging.LoggerFactory;
import com.alifi.crm.dal.guess.TransmitLogDAO;
import com.alifi.crm.dal.lottery.LogDAO;
import com.alifi.crm.dal.lottery.LotteryDAO;
import com.alifi.crm.dal.lottery.WinRecordDAO;
import com.alifi.crm.dal.object.LogDO;
import com.alifi.crm.dal.object.LotteryDO;
import com.alifi.crm.dal.object.TransmitLogDO;
import com.alifi.crm.dal.object.WinRecordDO;

public class LotteryzfManagerImpl implements LotteryzfManager {

    private static final Logger logger = LoggerFactory.getLogger(LotteryzfManagerImpl.class);
    private SimpleDateFormat   formatter   =   new   SimpleDateFormat   ("yyyy/MM/dd");
    private static Random       random = new Random();
    
    //中奖类型，与前面中奖活动区分开
    private static String TYPE ="2";

    @Autowired
    private LotteryDAO          lotteryDAO;

    @Autowired
    private WinRecordDAO        winRecordDAO;

    @Autowired
    private TransmitLogDAO      transmitLogDAO;

    @Autowired
    private LogDAO              logDAO;

    @Override
    public LotteryDO getEmployeeInfo(String employeeNum) {
    	//获取当前系统时间
        return lotteryDAO.selectByEmployeeNum(employeeNum,  GetFormateDate());
    }
    
    private String GetFormateDate() {
    	     
    	 Date   curDate   =   new   Date(System.currentTimeMillis());//获取当前时间     
    	return formatter.format(curDate);     
    }
    
    private String getFormateDate(Date curDate) {
    	SimpleDateFormat   formatter2   =   new   SimpleDateFormat   ("yyyy/MM/dd HH:mm:ss");
    	//Date   curDate   =   new   Date(System.currentTimeMillis());//获取当前时间     
   	return formatter2.format(curDate);     
   }

    @Override
    public List<WinRecordDO> getWinRecords() {
        List<WinRecordDO> winRecords = winRecordDAO.getWinRecords(TYPE, 100);
       
        
        for (Iterator<WinRecordDO> iterator = winRecords.iterator(); iterator.hasNext();) {
            WinRecordDO winRecordDO = (WinRecordDO) iterator.next();
            String curDate = formatter.format(winRecordDO.getGmtCreated());     
            int count = transmitLogDAO.countTransmitTimesByEmployeeNumByDate(winRecordDO.getEmployeeNum(),curDate);
            if(count <= 0){
                iterator.remove();
            }
        }
        
        return winRecords;
    }

    @Override
    public LotteryzfResult lottery(String employeeNum, String nickName, String realName) {
    	List<LotteryDO>  lotteryList = lotteryDAO.selectByEmployeeNumList(employeeNum,  GetFormateDate());
        if(lotteryList == null || lotteryList.size() == 0){
            return LotteryzfResult.不能抽奖;
        }
        LotteryDO lotteryDO = new LotteryDO();
        int iChoujiang = 0;
        for(LotteryDO tempDo : lotteryList) {
        	if(tempDo.getLotteryTime() == 1){
        		iChoujiang += 1;
        	} else {
        		lotteryDO.setCreator(tempDo.getCreator());
        		lotteryDO.setEmployeeNum(tempDo.getEmployeeNum());
        		lotteryDO.setGmtCreated(tempDo.getGmtCreated());
        		lotteryDO.setGmtModified(tempDo.getGmtModified());
        		lotteryDO.setLotteryTime(tempDo.getLotteryTime());
        		break;
        	}
        }
        if(iChoujiang == lotteryList.size()){
            return LotteryzfResult.已经抽奖过;
        }
        
        //大奖 
        int rd = random.nextInt(100);
        LotteryzfResult result = null;
        if(rd == 1) {
        	result = LotteryzfResult.阿里金仔;//1%
        }
        else if(rd >= 2 && rd <= 4){
                result = LotteryzfResult.阿里巴巴LOGO雨伞;//3%
        }
        //10积分宝
        //rd = random.nextInt(100);
        else if(rd >= 5 && rd <= 12){
                result = LotteryzfResult.ten元集分宝;//8%
        }
        //5元积分宝
        //rd = random.nextInt(100);
        else if(rd >= 13 && rd <= 70){
                result = LotteryzfResult.one元集分宝;//55%
        } else {//一元积分宝
        	result = LotteryzfResult.five元集分宝;//30%
        }
        //插入中奖纪录
        insertWinRecord(employeeNum, nickName, realName, result.code());
        String startTime = getFormateDate(lotteryDO.getGmtCreated());
        String endTime = getFormateDate(lotteryDO.getGmtModified());
        //更新抽奖次数
        lotteryDAO.updateLotterCurTime(lotteryDO.getEmployeeNum(), startTime, endTime);
        return result;
    }
    
    private void insertWinRecord(String employeeNum, String nickName, String realName,String prizeType){
        //插入中奖纪录
        WinRecordDO winRecord = new WinRecordDO();
        winRecord.setEmployeeNum(employeeNum);
        winRecord.setNickName(nickName);
        winRecord.setPrizeType(prizeType);
        winRecord.setRealName(realName);
        winRecord.setType(TYPE);
        winRecordDAO.insertWinRecord(winRecord);
    }

    @Override
    public void addTransmitLog(String employeeNum, String recipient) {
        if (StringUtil.isBlank(employeeNum) || StringUtil.isBlank(recipient)) {
            logger.error("employeeNum or recipient is null");
            return;
        }
        //自己不能给自己增加次数
        if (StringUtil.equalsIgnoreCase(employeeNum, recipient)) {
            if (logger.isInfoEnabled()) {
                logger.info("employeeNum is equal to recipient, employeeNum=" + employeeNum);
            }
            return;
        }
        //同一个人点多次不会增加次数
        if (transmitLogDAO.selectByEmployeeNumAndRecipient(employeeNum, recipient) != null) {
            if (logger.isInfoEnabled()) {
                logger.info("this body has already transmited, employeeNum=" + employeeNum
                            + ",recipient=" + recipient);
            }
            return;
        }

        //增加转发
        transmitLogDAO.save(genTransmitLogDO(employeeNum, recipient));
    }

    private TransmitLogDO genTransmitLogDO(String employeeNum, String recipient) {
        TransmitLogDO transmitLogDO = new TransmitLogDO();
        transmitLogDO.setEmployeeNum(employeeNum);
        transmitLogDO.setRecipient(recipient);
        return transmitLogDO;
    }

    @Override
    public List<WinRecordDO> selectByEmployeeNum(String employeeNum) {
        List<WinRecordDO> winRecord = winRecordDAO.selectByEmployeeByDate(employeeNum, TYPE, GetFormateDate());
        
        /*
        for (Iterator<WinRecordDO> iterator = winRecord.iterator(); iterator.hasNext();) {
            WinRecordDO winRecordDO = (WinRecordDO) iterator.next();
            int count = transmitLogDAO.countTransmitTimesByEmployeeNum(winRecordDO.getEmployeeNum());
            if(count <= 0){
                iterator.remove();
            }
        }*/
        return winRecord;
    }

    @Override
    public void insertLog(String employeeNum, String realName, String nickName) {
        LogDO logDO = new LogDO();
        logDO.setEmployeeNum(employeeNum);
        logDO.setNickName(nickName);
        logDO.setRealName(realName);
        logDAO.insertLog(logDO);
    }

}
